﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UPPERIOC.UPPER.enums;
using UPPERIOC.UPPER.UFileLog.IConfiguation;
using System.IO;
using UPPERIOC.UPPER.MainApplication.Log_;

namespace UPPERIOC.UPPER.UFileLog.DefineLog
{
    public class FileLog : ILog
    {
        IFileLogConfiguation Config;

        public FileLog(IFileLogConfiguation? Config)
        {
            if (Config == null)
            {
                throw new Exception("请将FileLog的配置类IFileLogConfiguation 实现交托容器管理");
            }
            this.Config = Config;
            logt = Config.WhichTypePrint?.ToArray();
        }
        LogType[]? logt;
        public LogType[] CanLogType { get {
                if (logt == null)
                {
                    return new LogType[0];
                }
                return logt;
            }
        }

        public void Log(LogType LogType, string Msg)
        {
            lock (Config)
            {
                var logtime = DateTime.Now;
                //路径
                var diname = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Config.DirectoryName);
                DirectoryInfo di = new DirectoryInfo(diname);
                if (!Directory.Exists(diname))
                {
                    Directory.CreateDirectory(diname);
                }
                //文件名
                var muti = "";
                if (Config.MutiFileName)
                {
                    muti = LogType.ToString();
                }
                var filename =  muti+ logtime.ToString(Config.FileNameTimeFormat) + Config.DefaultExt;
                DelTimeOutLog(di, logtime);
                var fullname = Path.Combine(diname, filename);
                if (!File.Exists(fullname))
                {
                    File.Create(fullname).Close();
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(Enum.GetName(LogType.GetType(), LogType));
                sb.Append(" - ");
                var sbf = "HH:mm:ss";
                if (Config.PrintMs)
                {
                    sbf += ":ffff";

                }

                sb.Append(logtime.ToString(sbf));
                sb.Append(":");
                sb.Append(Msg);
                sb.Append("\n");
                File.AppendAllText(fullname, sb.ToString());
            }
        }

        private void DelTimeOutLog(DirectoryInfo di, DateTime now)
        {
            foreach (var item in di.GetFiles())
            {
                if ((now - item.LastWriteTime).TotalHours > Config.HowManyHourSave)
                {
                    try
                    {

                        item.Delete();
                    }
                    catch (Exception)
                    {

                    }
                }
            }
        }
    }
}
